<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");

//custom includes (page specific code/functions)
include("include/newzbook/fileman.php");

//get all the configuration variables (custom function in newzbook.php include)
getConfigVars();  

//try to set the memory limit based on the configuration setting
if(ini_set("memory_limit",$config_memory_limit)!=TRUE){ 
    echo "Could not set memory to ".$config_memory_limit."B<br />\n"; 
}

//if the form was just posted back, let's use the form variables - otherwise the ones above will be used
if(isset($_POST['newzbin_name'])){
    $config_newzuname = $_POST['newzbin_name'];
}
if(isset($_POST['newzbin_name'])){
    $config_newzpw = $_POST['newzbin_pass'];
}
if(isset($_POST['NZBDropPath'])){
    $config_NZBDropPath = $_POST['NZBDropPath'];
}
if(isset($_POST['deleteupondl'])){
    $config_deleteupondl = $_POST['deleteupondl'];
}
//Get all the URL parameters (_GET)
if(isset($_GET['action'])) {
  $action = $_GET['action'];
}
if(isset($_GET['reportid'])) {
  //get the content of the URL parameter
  $newzbinreportID = $_GET['reportid'];
  //check if the content looks like a URL
  if(preg_match('/http\:\/\//',$newzbinreportID)){
    //if the content looks like a URL, let's try to parse out the reportID
    preg_match('/\/post\/([0-9]+)\//',$newzbinreportID,$matches);
    $newzbinreportID = $matches[1];
  }
}
if(isset($_GET['mode'])){
    $mode = $_GET['mode'];
}


/**********************************************************************\
 *           Setup the core variables                                 *
 * path:            The path (not including the final folder)         *
 *                  ex: /share                                        *
 * file:            the specific file to be played/viewed/downloaded  *
 *                  ex: file.txt                                      *
 * folder:          the folder - this is for historical purposes      *
 *                  ex: folder                                        *
 * fullpath:        the full path including the final folder (no file)*
 *                  ex: /share/folder                                 *
 * fullpathToFile:  full path to the file                             *
 *                  ex: /share/folder/file.txt                        *
 * dirlist:         list of files in the fullpath                     *
\**********************************************************************/
//get the path
if(isset($_GET['path'])){
    if($_GET['path'] !=""){
      $path = $_GET['path'];
    }
    else $path = $config_filemandefaultpath;
}
else {
    $path = $config_filemandefaultpath;
}

//get the folder and file
if(isset($_GET['file'])){
    $file = $_GET['file'];
}
if(isset($_GET['folder'])){
    $folder = $_GET['folder'];
}

if(isset($folder)){
    //The folder is set -- creating the full path...
    $fullpath = $path."/".$folder;
    if(isset($file)){
        $fullpathToFile = $fullpath."/".$file;
    }
}
else{
    //The folder isn't set, so we'll make the full path the same as the path...
    $fullpath = $path;
    if(isset($file)){
        $fullpathToFile = $fullpath."/".$file;
    }
}

//scan the directory
$dirlist = scandir($fullpath);
    
//setup the file extensions before running the loop
$audioext = array("mp3","wma","aac","aif","flac","iff","m4a","m4b","m4r","mid","midi","mod","mpa","ogg","ptf","ra","ram","rmj","sib","snd","wav");
$videoext = array("mkv","wmv","avi","3g2","3gp","asf","asx","divx","dvr-ms","f4v","fbr","flv","m4v","mov","mp4","mpeg","mpg","mts","ogm","qt","rcproject","rm","rmvb","smil","srt","stx","swf","ts","vob","vro","xvid");
$photoext = array("xcf","tif","thm","tga","tex","svgz","svg","stl","shp","sdb","qxp","qxd","psp","psd","ps","ppm","png","pln","pdf","pct","obj","mng","mb","max","ma","jpx","jpg","jpeg","inx","indd","hdp","gif","fxg","fpf","exif","eps","emz","emf","dxf","dwg","drw","dng","dgn","cr2","cpt","cdr","br5","bmp","blend","art","ai","abm","3dmf","3dm");
$basicext = array("nfo","txt","wps","wpd","sig","rtf","pages","opml","msg","lst","log","lit","docx","doc");
$configext = array("themepack","reg","rdf","psf","prx","properties","prf","ini","icc","cfg","conf");
  
  /***********************************************************\
   *           Actions for generating a playlist             *
  \***********************************************************/
  if($action == "generateplaylist"){
      generatePlaylist();
  }
  if(isset($file) && isset($action)){
    /*****************************************************\
     *     Stream Thumbnail (calls generate and save)    *
    \*****************************************************/
      if($action == "streamthumb"){
          streamThumb();
      }
    /***********************************************************\
     *   Generate a new thumbnail and stream - don't save it   *
    \***********************************************************/
      elseif($action == "generatethumb"){
          //generateThumb();
      }
    /***********************************************************\
     *       Actions for downloading or streaming content      *
    \***********************************************************/      
      elseif($action == "download" || $action == "stream"){
          downloadFile();
      }
  }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
    <? standardHead("File Manager");
    if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ ?>
    <link type="text/css" href="style/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />	
		<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
    <script>
        $(document).ready(function(){
            //Hide the controllers upon loading
                $(".sidecontroller").hide();
                $('.sideplaylist').hide();
                $('.nowplaying').hide();
                $('.toggles').hide();
            var animationType = 'drop';
            $(".sidecontrollertoggle").click(function () { 
                $('.sidecontroller').toggle(animationType,null,500);
            });
            $(".sideplaylisttoggle").click(function () { 
                $('.sideplaylist').toggle(animationType,null,500);
            });
            $(".nowplayingtoggle").click(function () { 
                $('.nowplaying').toggle(animationType,null,500);
            });
            $("#alltoggle").click(function () { 
                $('.sidecontroller').toggle(animationType,null,500);
                $('.sideplaylist').toggle(animationType,null,500);
                $('.nowplaying').toggle(animationType,null,500);
                //$('.toggles').toggle(animationType,null,500);
            });
            $(".toggle_toggles").click(function () { 
                $('.toggles').toggle(animationType,null,500);
            });
        });
    </script>
    <?php } ?>
</HEAD>

<BODY>
<?php internetSecurity(); ?>
<div style="visibility:hidden;display:none;" id="progress"><div id="progress_bg"></div><a name="loading" /><div id="progress_box"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt="loading...">You request is being processed...</div></div>
<div class="headercontent">
  <?php headerContent(); ?>
</div>
<div class="maincontent">
  Please send any questions or comments to <?php echo "<a href='mailto:".$cfg->get("Owner","email")."'>".$cfg->get("Owner","firstname")." ".$cfg->get("Owner","lastname")."</a>";?>.
  <br />
<div class="block">
  <h2>File Manager</h2>
  <?php
  echo "<h3>Now browsing: $fullpath</h3>";
  
  /***********************************************\
   *          Various View Mode Links            *
  \***********************************************/
  //echo "<a href='fileman.php?&path=".urlencode($fullpath)."&action=downloadzip'><img src='images/compress.png'/>Download Folder as ZIP</a>";
  //echo " | ";
  //If we're not viewing the folder in gallery mode, let's show the link to allow the user to view the folder in gallery mode
  if($action != "viewgallery"){
      echo "<a href='fileman.php?&path=".urlencode($fullpath)."&action=viewgallery' 
               title='View this folder in gallery mode.'><img src='images/images.png'/>View as Gallery</a>";
  }
  //if we are viewing in gallery mode, let's give the user the option to view the folder in regular list mode
  if($action == "viewgallery"){
      echo "<a href='fileman.php?&path=".urlencode($fullpath)."' 
               title='View in list mode.'><img src='images/application_view_columns.png'/>View as List</a>";
  }
  echo " | ";
  echo "<select onChange=\"if(this.selectedIndex!=0 && this.selectedIndex!=2){
                                  self.location=this.options[this.selectedIndex].value
                              }
                              else if(this.selectedIndex==2){
                                  popupSmall(this.options[this.selectedIndex].value,'action')
                              }\">";
  echo "<option>Select an Action</option>";
  // Show the link for the playlist generator
  echo "<option value='fileman.php?&path=".urlencode($fullpath)."&action=generateplaylist'>Generate Playlist</option>";
  
  //Add folder to playlist
  echo "<option value='playlistmanager.php?action=addFolder&path=".urlencode($fullpath)."' 
                onClick=\"return popupSmall(this.selectedIndex,'action')\">Add folder to playlist</option>";
  
  //if Remote Play is enabled, show the Play Folder on PCH link
  if($remoteplayenabled){
      echo "<option value='fileman.php?&path=".urlencode($fullpath)."&action=remoteplay&mode=folder'>Play this folder on PCH</option>";
  }
  echo "</select>";
  echo "<br /><br />";


  /***********************************************\
   *       Remote Play Calls (if selected)       *
  \***********************************************/
  // If selected, send the remote play commands (before generating the sidebar HTML
  if($action == "remoteplay" && $mode == "playlist"){
      playFiles($_SESSION['playlist']);
      echo "<div class='infomessage'>Remote play of the playlist you created should start on the popcornhour shortly...</div>";
  }
  if($action == "remoteplay" && $mode == "folder"){
      if(isset($files)){
          unset($files);
      }
      //$dirlist = scandir($fullpath);
      foreach($dirlist as $file){
          $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
          //if it's an MP3, let's echo it out
          if(in_array($ext,$audioext)){
              //add the file to the files array
              $files[] = $fullpath."/".$file;
          }
      }
      playFiles($files);
      echo "<div class='infomessage'>Remote play of the folder \"$fullpath\" should start on the popcornhour shortly...</div>";
      //echo implode("<br />",$files); 
  }

  /***********************************************\
   *  Generate a zip download for the directory  *
  \***********************************************/
  if($action == "downloadzip"){
      generateZipFile();
  }

  if(isset($file) && isset($action)){
    /********************************************\
     *          Viewer (for text files)         *
    \********************************************/
      if($action == "view"){
          // create the back arrow
          echo "<a href='?path=".urlencode($path)."'><img src='images/arrow_left.png'/>..</a><br />";
          //get the contents of the file & display it in a pre (style it later)
          echo "<pre>".htmlentities(file_get_contents($fullpathToFile))."</pre>";
          
          //no need to complete the rest of the file checking
          die("</div></body></html>");
      }
    /********************************************\
     *          Play Song Remotely              *
    \********************************************/
	  elseif($action == "remoteplay" && $mode == "file"){
        //figure out the file type
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        
        //assign the option based on the filetype
        $optiontype = "unknown";
        
        //if it's a known type, play it
        if(in_array($ext,$audioext)){ 
            $option = "aod";
            $optiontype = "audio"; 
        }
        elseif(in_array($ext,$videoext)){ 
            $option = "vod";
            $optiontype = "video"; 
        }
        elseif(in_array($ext,$photoext)){
            $extimg = "picture.png"; 
        }
        else{ die("This is not a valid filetype to play.<br />File: $file <br /> Full path: $fullpath <br /></div></body></html>"); }
            
        echo "<div class='infomessage'>The file \"$file\" which is a $optiontype file should start playing on the popcornhour shortly...</div>";

        //play the song
        playFile($fullpathToFile,$option);
        
	  }
  }

  /***********************************************************************\
   *  Make sure we have a clean path and setup the back arrow            *
  \***********************************************************************/  
  //deleteme - maybe... need to double check this
  if($path != $fullpath && isset($file)){
      $dirlist = scandir($path);
  }
  //if the path is set, but the folder isnt
  if(isset($path) && !isset($folder)){
      //split out the folder from the path
      preg_match('/([^\.]+)\/([^\/]+)$/', $path, $matches);
      $path = $matches[1];
  }
  //deleteme
  //echo "Path: $path <br /> Fullpath: $fullpath <br /> File: $file <br /> Folder: $folder <br />";
  if($path != "") { echo "<a href='?path=".urlencode($path)."'><img src='images/arrow_left.png'/>..</a><br />"; }
  
  /********************************************\
   *          View in Gallery Mode            *
  \********************************************/
  if($action == "viewgallery"){
      //let's loop through the directory list
      foreach($dirlist as $item){
          //if the path is . lets take it out
          if($item != "." && $item != ".." && $item != ".album"){ 
              $dircheck = $fullpath."/".$item;
              if(is_dir($fullpath."/".$item)){
                  //check if it's an album
                  $albumImages = array("folder.jpg","AlbumArtSmall.jpg","front.jpg","back.jpg");
                  //setup a check variable
                  $artworkFound = false;
                  //look for one of the album image types
                  foreach($albumImages as $folderItem){
                      if(file_exists($fullpath."/".$item."/".$folderItem)){
                          echo "<a href='fileman.php?path=".urlencode($fullpath."/".$item)."'><img src='fileman.php?action=download&path=".urlencode($fullpath."/".$item)."&file=".urlencode($folderItem)."' class='albumArt' alt='$item'/></a>";
                          //echo "<a title='$item' class='alternativeArt'>$folderItem</a>"; //uncomment this to see which art was used
                          $artworkFound = true;
                          //exit the current loop
                          break;
                      }
                      else{
                      //is there any other potential artwork in the folder?
                      
                      }
                  }
                  if($artworkFound == false){
                      echo "<div class='alternativeArtHolder'><div class='alternativeArt'><a href='fileman.php?path=".urlencode($musicDirectory."/".$item)."'>$item</a></div></div>";
                  }
                  //echo "<a href='?folder=".urlencode($item)."&path=".urlencode($fullpath)."'><span class='thumbnail'><img src='images/folder.png'/> ".$item."</span></a>";
              }
              else{ 
                  //get the file type
                  $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
                  //if the filetype is one of our known types, let's associate an icon to it
                  if(in_array($ext,$audioext)){ $extimg = "music.png"; }
                  elseif(in_array($ext,$videoext)){ $extimg = "film.png"; }
                  elseif(in_array($ext,$photoext)){ $extimg = "picture.png"; }
                  elseif(in_array($ext,$configext)){ $extimg = "page_white_gear.png"; }
                  elseif(in_array($ext,$basicext)){ $extimg = "page_white_text.png"; }
                  else{ $extimg = "page_white_magnify.png"; }
                  //if the filetype is recognized, let's associate it with an icon
                  if($extimg == "page_white_text.png" || $extimg == "page_white_gear.png" || $extimg =="page_white_magnify.png"){
                    echo "<div class='alternativeArtHolder'><div class='alternativeArt'><a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=view'><img src='images/".$extimg."'/> ".$item."</a></div></div>";
                  }
                  elseif($extimg == "music.png"){
                    echo "<div class='alternativeArtHolder'><div class='alternativeArt'><a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=download'><img src='images/".$extimg."'/> ".$item."</a></div></div>";
                  }
                  elseif($extimg == "picture.png"){
                    echo "<div class='alternativeArtHolder'><div class='alternativeArt'><a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=download'>";
                    echo "<img src='fileman.php?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=streamthumb'/>";
                    //echo "<img src='fileman.php?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=generatethumb'/>";
                    echo $item."</a></div></div>";
                  }
                  else{
                    echo "<div class='alternativeArtHolder'><div class='alternativeArt'><img src='images/".$extimg."'/> ".$item."</div></div>";
                  }
              }
        } 
        //then kill the app before it outputs any more content
    }
    exit;
  }
    
  /********************************************\
   *          The basic list format           *
  \********************************************/  
  echo "<ul class='filelist'>";
  //For each item in the scan of the directory, let's check it
  foreach($dirlist as $item){
    //if the path is . lets take it out
    if($item == "." | $item == ".." | $item == ".album"){
        //do nothing with this
        //echo "This is a dot.<br />";
    }
    //otherwise we'll treat it based on if it's a file or folder
    else{
        $dircheck = $fullpath."/".$item;
        if(is_dir($fullpath."/".$item)){
            echo "<li class='icon icon_folder'><a href='?folder=".urlencode($item)."&path=".urlencode($fullpath)."'>".$item."</a></li>";
        }
        /*
        elseif(is_file($fullpath."/".$item)) {
            echo "<img src='images/page_white_magnify.png'/> ".$item."<br />"; 
        }
        */
        else{ //this was really only catching files >2 GB so I put all the file logic here
            //get the file type
            $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
            //if the filetype is one of our known types, let's associate an icon to it
            if(in_array($ext,$audioext)){ $extimg = "icon_audio"; }
            elseif(in_array($ext,$videoext)){ $extimg = "icon_video"; }
            elseif(in_array($ext,$photoext)){ $extimg = "icon_photo"; }
            elseif(in_array($ext,$configext)){ $extimg = "icon_config"; }
            elseif(in_array($ext,$basicext)){ $extimg = "icon_basic"; }
            else{ $extimg = "icon_view"; }
            //if the filetype is recognized, let's associate it with an icon
            if($extimg == "icon_config" || $extimg == "icon_basic" || $extimg == "icon_view"){
              echo "<li class='icon $extimg'><a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=view'>".$item."</a></li>";
            }
            elseif($extimg == "icon_photo" || $extimg == "icon_audio"){
              echo "<li  class='icon $extimg'>";
              //link to queue in playlist
              echo "<form action='?path=".urlencode($fullpath)."' method='post' style='display:inline;vertical-align:top;'><input type='hidden' name='addtoqueue' value='".htmlentities($fullpath."/".$item, ENT_QUOTES)."'><input type='image' src='images/add.png' value='Submit' alt='Submit'></form>";
              
              //remote play functionality
              if($extimg == "icon_audio" && $remoteplayenabled){
                  echo "<a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=remoteplay&mode=file'><img src='images/server_go.png'/></a>";
              }
              //standard icon and link
              echo "<a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=download'>".$item."</a>";
              echo "</li>";
            }
            elseif($extimg == "icon_video"){
                echo "<li class='icon $extimg'>";
                //link to queue in playlist
                echo "<form action='?path=".urlencode($fullpath)."' method='post' style='display:inline;vertical-align:top;'><input type='hidden' name='addtoqueue' value='".$fullpath."/".$item."'><input type='image' src='images/add.png' value='Submit' alt='Submit'></form>";
                
                //if remoteplay is enabled, create an icon to start the file playing on the popcornhour
                if($remoteplayenabled){
                    echo "<a href='?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=remoteplay&mode=file'><img src='images/server_go.png'/></a>";
                }
                
                //print out the extension icon and the filename (videos aren't links) 
                echo $item;
                echo "</li>";
            }
            else{
              echo "<li><img src='images/".$extimg."'/> ".$item."</li>";
            }
        }
    }
  }
  if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //the code below causes issues on the PCH
      /***********************************************\
       *       HTML for the various side bars        *
      \***********************************************/
      //the nowplaying or currentlyplaying display 
      if($action == "" || $action == "null" || !isset($action) || $action == "sendcommand" || $action == "remoteplay"){
          if($remoteplayenabled){
              //we'll capture the status of the nowPlaying (true/false) so we can decide whether or not to show the toggle link below
              $nowPlaying = nowPlaying();      
              //side controller is always output (if remoteplay is enabled)
              echo "<div class='sidecontroller'>";
                  displayController($fullpath);
                  echo "<div class='toggle_close'><a href='#' class='sidecontrollertoggle'><img src='images/cross.png'/></a></div>";
              echo "</div>";
          }
          //there is a check in the sidePlaylist function on if it should be shown
          sidePlaylist($fullpath, $remoteplayenabled);
      }
      
      /***********************************************\
       *      Toggles for the Sidebar Elements       *
      \***********************************************/
      //output the toggles for the side controller, now playing, and sideplaylist
      echo "<div class='toggles'>";
      if($nowPlaying){
          echo "<a href='#' class='nowplayingtoggle'>Now Playing</a> | ";
      }
      if($remoteplayenabled){
          echo "<a href='#' class='sidecontrollertoggle'>Side Controller</a> | ";
      }
      if(isset($_SESSION['playlist'])){
          echo "<a href='#' class='sideplaylisttoggle'>Side Playlist</a> | ";
      }
      ?>
      <a href='#' id='alltoggle'>All</a>
          <!-- <div class='toggle_close'><a href='#' class='toggle_toggles'><img src='images/cross.png'/></a></div> -->
      </div>
      <div class='toggle_toggle'>
          <a href='#' class='toggle_toggles'>Hide / Show</a>
      </div>
  <?php } ?>
</div>
</body>
</html>
<?php
/********************************************\
 *          functions at the end            *
\********************************************/
?>